package com.jwaoo.chat.session.pick.activity;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.dx.as.UI;
import com.dx.as.common.C;
import com.dx.as.common.CommonUtils;
import com.dx.as.common.ILoadListener;
import com.dx.as.common.file.AttachmentStore;
import com.dx.as.common.log.LogUtil;
import com.dx.as.common.storage.StorageUtil;
import com.dx.as.common.string.StringUtil;
import com.dx.as.upload.DownloadManager;
import com.dx.as.upload.OnDownloadListener;
import com.jwaoo.chat.ChatConstants;
import com.jwaoo.chat.Message;
import com.jwaoo.chat.R;
import com.jwaoo.chat.attachment.FileAttachment;
import com.jwaoo.chat.bitmap.BitmapDecoder;
import com.jwaoo.chat.bitmap.ImageUtil;
import com.jwaoo.chat.data.db.MessageHandler;
import com.jwaoo.chat.ui.imageview.BaseZoomableImageView;
import com.jwaoo.chat.ui.imageview.ImageGestureListener;
import com.jwaoo.media.dialog.CustomAlertDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 查看聊天消息原图
 * Created by huangjun on 2015/3/6.
 */
public class WatchMessagePictureActivity extends UI {

    private static final String INTENT_EXTRA_IMAGE = "INTENT_EXTRA_IMAGE";
    private static final String TAG = WatchMessagePictureActivity.class.getSimpleName();
    private Message message;
    private List<Message> imageMsgList = new ArrayList<>();
    private int firstDisplayImageIndex = 0;
    private boolean newPageSelected = false;
    private View loadingLayout;
    private TextView progressText;
    private BaseZoomableImageView image;
    protected CustomAlertDialog alertDialog;
    private ViewPager imageViewPager;
    private PagerAdapter adapter;

    public static void start(Context context, Message message) {
        Intent intent = new Intent();
        intent.putExtra(INTENT_EXTRA_IMAGE, message);
        intent.setClass(context, WatchMessagePictureActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nim_watch_picture_activity);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.message = (Message) getIntent().getSerializableExtra(INTENT_EXTRA_IMAGE);
        progressText = findView(R.id.progress);
        findViews();
        queryImageMessages();
    }

    @Override
    protected void onDestroy() {
        imageViewPager.setAdapter(null);
        super.onDestroy();
    }

    private void queryImageMessages() {
        MessageHandler.getInstace(getApplicationContext()).handlerMessages(MessageHandler.GET_MESSAGE_IMG,message.getFriend(), new ILoadListener<Object>() {
            @Override
            public void onResponse(Object response, int flg) {
                if (response != null){
                    List<Message> param = (List<Message>) response;
                    imageMsgList.addAll(param);
                    Collections.reverse(imageMsgList);
                    setDisplayIndex();
                    setViewPagerAdapter();
                }
            }
            @Override
            public void onFailure(Throwable t) {

            }
        });

    }

    // 设置第一个选中的图片index
    private void setDisplayIndex() {
        for (int i = 0; i < imageMsgList.size(); i++) {
            Message imageObject = imageMsgList.get(i);
            if (compareObjects(message, imageObject)) {
                firstDisplayImageIndex = i;
                break;
            }
        }
    }

    protected boolean compareObjects(Message t1, Message t2) {
        return (t1.getMsgid() == t2.getMsgid());
    }

    private void findViews() {
        alertDialog = new CustomAlertDialog(this);
        loadingLayout = findViewById(R.id.loading_layout);

        imageViewPager = (ViewPager) findViewById(R.id.view_pager_image);
    }

    private void setViewPagerAdapter() {
        adapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return imageMsgList == null ? 0 : imageMsgList.size();
            }

            @Override
            public void notifyDataSetChanged() {
                super.notifyDataSetChanged();
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                View layout = (View) object;
                BaseZoomableImageView iv = (BaseZoomableImageView) layout.findViewById(R.id.watch_image_view);
                iv.clear();
                container.removeView(layout);
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return (view == object);
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                ViewGroup layout;
                layout = (ViewGroup) LayoutInflater.from(WatchMessagePictureActivity.this).inflate(R.layout.image_layout_multi_touch, null);

                layout.setBackgroundColor(Color.BLACK);

                container.addView(layout);
                layout.setTag(position);
                if (position == firstDisplayImageIndex) {
                    onViewPagerSelected(position);
                }

                return layout;
            }

            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }
        };

        imageViewPager.setOffscreenPageLimit(2);
        imageViewPager.setAdapter(adapter);
        imageViewPager.setCurrentItem(firstDisplayImageIndex);
        imageViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (positionOffset == 0f && newPageSelected) {
                    newPageSelected = false;
                    onViewPagerSelected(position);
                }
            }

            @Override
            public void onPageSelected(int position) {
                newPageSelected = true;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void onViewPagerSelected(int position) {
        updateCurrentImageView(position);
        onImageViewFound(image);
        requestOriImage(imageMsgList.get(position));
    }

    // 初始化每个view的image
    protected void updateCurrentImageView(final int position) {
        View currentLayout = imageViewPager.findViewWithTag(position);

        if (currentLayout == null) {
            ViewCompat.postOnAnimation(imageViewPager, new Runnable() {

                @Override
                public void run() {
                    updateCurrentImageView(position);
                }
            });
            return;
        };
        image = (BaseZoomableImageView) currentLayout.findViewById(R.id.watch_image_view);
    }

    // 若图片已下载，直接显示图片；若图片未下载，则下载图片
    private void requestOriImage(Message msg) {
        Bitmap bitmap = ImageLoader.getInstance().getMemoryCache().get(msg.getAttachment().getThumbnail());
        if (bitmap != null) {
            image.setImageBitmap(bitmap);
        }

        if (isOriginImageHasDownloaded(msg)) {
            onDownloadSuccess(msg);
            return;
        }

        // async download original image
        onDownloadStart(msg);
        message = msg; // 下载成功之后，判断是否是同一条消息时需要使用
//        downloadFuture = NIMClient.getService(MsgService.class).downloadAttachment(msg, false);
    }

    private boolean isOriginImageHasDownloaded(final Message message) {
        if (message.getAttachment().getAttachstate() == ChatConstants.transferred &&
                !TextUtils.isEmpty((message.getAttachment()).getPath())) {
            return true;
        }
        return false;
    }

    /**
     * ******************************** 设置图片 *********************************
     */

    private void setThumbnail(Message msg) {
        String thumbPath = msg.getAttachment().getThumbnail();
        String path = msg.getAttachment().getPath();
        Bitmap bitmap = null;
        if (!TextUtils.isEmpty(thumbPath)) {
            bitmap = BitmapDecoder.decodeSampledForDisplay(thumbPath);
            bitmap = ImageUtil.rotateBitmapInNeeded(thumbPath, bitmap);
        } else if (!TextUtils.isEmpty(path)) {
            bitmap = BitmapDecoder.decodeSampledForDisplay(path);
            bitmap = ImageUtil.rotateBitmapInNeeded(path, bitmap);
        }

        if (bitmap != null) {
            image.setImageBitmap(bitmap);
            return;
        }

        image.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnLoading()));
    }

    private void setImageView(Message msg) {

        String path = msg.getAttachment().getPath();
        if (TextUtils.isEmpty(path)) {
            image.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnLoading()));
            return;
        }
        Bitmap bitmap = BitmapDecoder.decodeSampledForDisplay(path, false);
        bitmap = ImageUtil.rotateBitmapInNeeded(path, bitmap);
        if (bitmap == null) {
            Toast.makeText(this, R.string.picker_image_error, Toast.LENGTH_LONG).show();
            image.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnFailed()));
        } else {
            image.setImageBitmap(bitmap);
        }
    }

    private int getImageResOnLoading() {
        return R.drawable.nim_image_default;
    }

    private int getImageResOnFailed() {
        return R.drawable.nim_image_download_failed;
    }

    /**
     * ********************************* 下载 ****************************************
     */

    private void onDownloadStart(final Message msg) {
        setThumbnail(msg);
        if(TextUtils.isEmpty(msg.getAttachment().getPath())){
            loadingLayout.setVisibility(View.VISIBLE);
        } else {
            loadingLayout.setVisibility(View.GONE);
        }

        if (!DownloadManager.isDownloading(message.getMsgid()) || message.getAttachment().getAttachstate() == ChatConstants.fail){
            MessageHandler.getInstace(getApplicationContext()).handlerAttachmentMessage(message);
            Log.e("==",""+message.getAttachment().getUrl());

        }
        Log.e("==","path:"+message.getAttachment().getPath());
//        DownloadManager.removeDownload(message.getMsgid());
        DownloadManager.addDownloadListener(message.getMsgid(), getOnDownloadListener(msg));

    }

    private OnDownloadListener getOnDownloadListener(final Message msg){
        return new OnDownloadListener() {
            @Override
            public void onDownloadFailed() {
                if (msg == message){
                    downloadFailed();
                }
            }

            @Override
            public void onDownSuccess() {
                String dir = CommonUtils.getImgDir(getApplicationContext());
                String path = CommonUtils.getFilePath(dir,msg.getAttachment().getUrl());
                for (Message message : imageMsgList){
                    if (message.getMsgid() == msg.getMsgid()){
                        message.getAttachment().setAttachstate(ChatConstants.transferred);
                        message.getAttachment().setPath(path);
                        break;
                    }
                }
                if (msg.getMsgid() == message.getMsgid()){
                    onDownloadSuccess(message);
                }
            }

            @Override
            public void onDownProgress(final long progress,final long total) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressText.setText(StringUtil.getPercentString(progress * 100/total));
                        LogUtil.d("WathPicture","progress : "+progress * 100/total);
                    }
                });
            }
        };
    }


    private void onDownloadSuccess(final Message msg) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadingLayout.setVisibility(View.GONE);
                setImageView(msg);
            }
        });
    }

    private void downloadFailed() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadingLayout.setVisibility(View.GONE);
                image.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnFailed()));
                Toast.makeText(WatchMessagePictureActivity.this, R.string.download_picture_fail, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * ***********************************图片点击事件*******************************************
     */

    // 设置图片点击事件
    protected void onImageViewFound(BaseZoomableImageView imageView) {
        imageView.setImageGestureListener(new ImageGestureListener() {

            @Override
            public void onImageGestureSingleTapConfirmed() {
                onImageViewTouched();
            }

            @Override
            public void onImageGestureLongPress() {
                showWatchPictureAction();
            }

            @Override
            public void onImageGestureFlingDown() {
                finish();
            }
        });
    }

    // 图片单击
    protected void onImageViewTouched() {
        finish();
    }

    // 图片长按
    protected  void showWatchPictureAction() {
        if (alertDialog.isShowing()) {
            alertDialog.dismiss();
            return;
        }
        alertDialog.clearData();
        String path = message.getAttachment().getThumbPath();
        if (TextUtils.isEmpty(path)) {
            return;
        }
        String title;
        if (!TextUtils.isEmpty( message.getAttachment().getPath())) {
            title = getString(R.string.save_to_device);
            alertDialog.addItem(title, new CustomAlertDialog.onSeparateItemClickListener() {

                @Override
                public void onClick() {
                    savePicture();
                }
            });
        }
        alertDialog.show();
    }

    // 保存图片
    public void savePicture() {
        FileAttachment attachment = message.getAttachment();
        String path = attachment.getPath();
        if (TextUtils.isEmpty(path)) {
            return;
        }

        String srcFilename = attachment.getFileName();
        //默认jpg
        String extension = TextUtils.isEmpty(attachment.getExtension()) ? "jpg" : attachment.getExtension();
        srcFilename += ("." + extension);

        String picPath = StorageUtil.getSystemImagePath();
        String dstPath = picPath + srcFilename;
        if (AttachmentStore.copy(path, dstPath) != -1) {
            try {
                ContentValues values = new ContentValues(2);
                values.put(MediaStore.Images.Media.MIME_TYPE, C.MimeType.MIME_JPEG);
                values.put(MediaStore.Images.Media.DATA, dstPath);
                getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                Toast.makeText(WatchMessagePictureActivity.this, getString(R.string.picture_save_to), Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                // may be java.lang.UnsupportedOperationException
                Toast.makeText(WatchMessagePictureActivity.this, getString(R.string.picture_save_fail), Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(WatchMessagePictureActivity.this, getString(R.string.picture_save_fail), Toast.LENGTH_LONG).show();
        }
    }
}
